<template>
  <el-container
    direction="vertical"
    style="min-height: 100%; background-color: #f6f6f6"
  >
    <el-affix>
      <MainHeader @idChange="handleIdChange" />
      <el-card shadow="Never" style="margin-bottom: 3px">
        <h1 style="margin: 0">{{ questionTitle }}</h1>
      </el-card>
    </el-affix>

    <div style="width: 1300px; margin: auto">
      <v-md-editor
        v-model="answerInput"
        autofocus="true"
        height="700px"
        left-toolbar="undo redo clear | h bold italic | quote ul ol table hr link myCode | image"
        right-toolbar="preview | toc"
        @upload-image="uploadImage"
        :disabled-menus="[]"
      />
    </div>
    <el-footer style="height: 60px; margin-top: 20px; background-color: white">
      <el-button
        type="primary"
        @click="answerCommit"
        style="width: 300px; height: 40px; margin: 10px"
      >
        发布回答
      </el-button>
    </el-footer>
  </el-container>
</template>

<script setup>
import { ref } from "vue";
import MainHeader from "@/components/common/MainHeader.vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { useRouter } from "vue-router";
import $ from "jquery";
import axios from "axios";

const answerInput = ref(""),
    router = useRouter()

const questionId = ref(""),
  questionTitle = ref("");

const uploadImage = (event, insertImage, files) => {
  let data = new FormData();
  data.append("img", files[0]);
  data.append("type", "a");
  data.append("id", "1");
  data.append("name", null);
  $.ajax({
    type: "post",
    async: false,
    url: "http://150.158.52.191:8081/ReceivePicture",
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    dataType: "json",
    success: function (resp) {
      insertImage({
        url: resp.url,
        desc: files[0].name,
        width: 200,
        height: 200,
      });
    },
    error: function (errorMsg) {
      console.log(errorMsg);
    },
  });
};

const answerCommit = () => {
  const ANSWER = answerInput.value.trim();
  if (ANSWER === "") ElMessage.warning("回答内容不能为空");
  else if (ANSWER.length < 20) ElMessage.warning("回答内容不应少于30个字符");
  else {
    ElMessageBox.confirm("是否确认提交回答？", "请确认", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "info",
    })
      .then(() => {
        axios
          .post(
            "http://localhost:8080/answer",
            JSON.stringify({
              user_id: JSON.parse(localStorage.getItem("user")).id,
              question_id: questionId.value,
              answer_content: ANSWER,
            }),
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((r) => {
            const resp = r.data;
            if (resp.status === 0) {
              ElNotification.success("发布回答成功，即将跳回问题详情页面");
              setTimeout(() => {
                router.push({
                  path: '/QuestionDetail',
                  query: {
                    question_id: questionId.value
                  }
                })
              }, 1000)
            } else {
              ElNotification.error("发布回答失败，请检查网络连接是否正常");
            }
          })
          .catch((error) => {
            console.log(error.request);
            ElNotification.error("发布回答失败，请检查网络连接是否正常");
          });
      })
      .catch(() => {});
  }
};

const handleIdChange = (query) => {
  questionId.value = query.question_id;
  questionTitle.value = query.title;
};
</script>

<style scoped>
:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
}
:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 0;
}
:deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 0;
}
.answer-input {
  width: 68%;
  margin: auto;
  font-size: 16px;
  background-color: #fff;
}
</style>
